package org.hako.recite.word.input;

import java.util.HashMap;
import java.util.Map;

/**
 * Dictionary prefix matcher.
 * 
 * @since 0.4.4
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class DictionaryPrefixMatcher implements PrefixMatcher {

	private Map<String, String> dictMap;
	private int length;

	/**
	 * Create
	 * 
	 * @param length
	 *            the length to match
	 */
	public DictionaryPrefixMatcher(int length) {
		super();
		dictMap = new HashMap<String, String>();
		this.length = length;
	}

	@Override
	public boolean check(String roma, int index, int length) {
		int remaining = length - index;
		if (remaining < this.length) {
			return false;
		}
		String part = roma.substring(index, index + this.length);
		return dictMap.containsKey(part);
	}

	@Override
	public String match(String roma, int index) {
		return dictMap.get(roma.substring(index, index + length));
	}

	/**
	 * Add mapping to dictionary.
	 * 
	 * @param roma
	 * @param nihongo
	 */
	public void addMapping(String roma, String nihongo) {
		dictMap.put(roma, nihongo);
	}

	/**
	 * Add mapping to dictionary.
	 * 
	 * @param mapping
	 */
	public void addMapping(Map.Entry<String, String> mapping) {
		addMapping(mapping.getKey(), mapping.getValue());
	}

	@Override
	public int getStepLength() {
		return length;
	}

}
